/**
 * About Store 辅助函数
 * 提供通用的多语言处理和数据获取逻辑
 */

interface MultiLangItem {
  [key: string]: any
}

/**
 * 根据语言获取多语言字段值的通用函数
 */
export const getMultiLangField = (
  item: MultiLangItem | undefined,
  fieldPrefix: string,
  lang: string,
  fallback: string | number = ''
): string => {
  if (!item) return String(fallback)
  
  const langMap: Record<string, string> = {
    'en': '_en',
    'es': '_es',
    'ja': '_ja'
  }
  
  const suffix = langMap[lang] || '_en'
  const key = `${fieldPrefix}${suffix}`
  
  return String(item[key] || item[`${fieldPrefix}_en`] || fallback)
}

/**
 * 获取页面基础信息的通用函数
 */
export const getPageInfo = (
  settings: Record<string, any>,
  pagePrefix: string,
  lang: string
) => {
  return {
    title: getMultiLangField(settings, `${pagePrefix}_title`, lang),
    subtitle: getMultiLangField(settings, `${pagePrefix}_subtitle`, lang),
    description: getMultiLangField(settings, `${pagePrefix}_description`, lang),
    sectionTitle: getMultiLangField(settings, `${pagePrefix}_section_title`, lang),
    contentDescription: getMultiLangField(settings, `${pagePrefix}_content_description`, lang)
  }
}

/**
 * 获取特性文本的通用函数
 */
export const getFeatureText = (
  feature: { text_en: string; text_es: string; text_ja: string },
  lang: string
): string => {
  return String(getMultiLangField(feature, 'text', lang, feature.text_en))
}

/**
 * 获取统计标签的通用函数
 */
export const getStatLabel = (
  stat: { label_en: string; label_es: string; label_ja: string },
  lang: string
): string => {
  return String(getMultiLangField(stat, 'label', lang, stat.label_en))
}

/**
 * 获取认证描述的通用函数
 */
export const getCertificationDescription = (
  cert: { description_en: string; description_es: string; description_ja: string },
  lang: string
): string => {
  return String(getMultiLangField(cert, 'description', lang, cert.description_en))
}

/**
 * 安全解析JSON的工具函数
 */
export const safeParseJSON = <T>(value: string, fallback: T): T => {
  try {
    return JSON.parse(value)
  } catch {
    return fallback
  }
}